from typing import Dict, Any, List


class Analytics:
    """简单的统计/分析组件

    提供按课程的统计信息（基于当前内存中的管理器数据）。
    该类依赖注入 LMSSystem（或包含 course_manager/enrollment_manager/assignment_manager）。
    """
    def __init__(self, system):
        self.system = system

    def get_course_statistics(self, course_id: str) -> Dict[str, Any]:
        """返回课程统计信息字典

        结果字段包括：course_id, course_name, enrolled_count, assignments_count,
        submissions_count, average_score（如果没有分数则为 None）
        """
        cm = self.system.course_manager
        em = self.system.enrollment_manager
        am = self.system.assignment_manager

        course = cm.get_course(course_id) if cm else None
        if course is None:
            return {}

        # enrollment stats
        enrolled = 0
        if em:
            enroll_stats = em.get_enrollment_statistics(course_id)
            enrolled = enroll_stats.get('active_enrollments', 0)
        else:
            enrolled = len(getattr(course, 'student_ids', []))

        # assignments and submissions
        assignments = []
        submissions_count = 0
        grades: List[float] = []
        if am:
            for a in am.assignments.values():
                try:
                    if getattr(a, 'course_id', None) == course_id:
                        assignments.append(a)
                        subs = am.get_submissions(a.assignment_id)
                        submissions_count += len(subs)
                        for s in subs:
                            if getattr(s, 'grade', None) is not None:
                                grades.append(float(s.grade))
                except Exception:
                    continue

        avg_score = None
        if grades:
            avg_score = sum(grades) / len(grades)

        return {
            'course_id': course_id,
            'course_name': getattr(course, 'name', getattr(course, 'title', '')),
            'enrolled_count': enrolled,
            'assignments_count': len(assignments),
            'submissions_count': submissions_count,
            'average_score': avg_score,
        }
